"""Task storage and persistence management."""

import json
import os
from pathlib import Path
from typing import List
from .models import Task, TaskManager, TaskStatus


class TaskStorage:
    """Handles task persistence to JSON file."""
    
    def __init__(self, data_file: str = None):
        """Initialize storage with data file path."""
        if data_file is None:
            # Store in user's home directory
            home_dir = Path.home()
            self.data_file = home_dir / ".task_manager_data.json"
        else:
            self.data_file = Path(data_file)
    
    def save_tasks(self, task_manager: TaskManager) -> bool:
        """Save task manager state to file."""
        try:
            data = {
                "tasks": [task.to_dict() for task in task_manager.tasks],
                "next_id": task_manager.next_id,
                "benchmark_id": task_manager.benchmark_id,
                "completion_history": task_manager.completion_history
            }
            
            with open(self.data_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"Error saving tasks: {e}")
            return False
    
    def load_tasks(self) -> TaskManager:
        """Load task manager state from file."""
        task_manager = TaskManager()
        
        if not self.data_file.exists():
            return task_manager
        
        try:
            with open(self.data_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # Load tasks
            for task_data in data.get("tasks", []):
                task = Task.from_dict(task_data)
                task_manager.tasks.append(task)
            
            # Load other state
            task_manager.next_id = data.get("next_id", 1)
            task_manager.benchmark_id = data.get("benchmark_id")
            task_manager.completion_history = data.get("completion_history", [])
            
            return task_manager
        except Exception as e:
            print(f"Error loading tasks: {e}")
            return TaskManager()
    
    def backup_tasks(self) -> bool:
        """Create a backup of current tasks."""
        if not self.data_file.exists():
            return False
        
        try:
            backup_file = self.data_file.with_suffix('.json.backup')
            import shutil
            shutil.copy2(self.data_file, backup_file)
            return True
        except Exception as e:
            print(f"Error creating backup: {e}")
            return False
    
    def clear_tasks(self) -> bool:
        """Clear all saved tasks."""
        try:
            if self.data_file.exists():
                self.data_file.unlink()
            return True
        except Exception as e:
            print(f"Error clearing tasks: {e}")
            return False